package com.fc.mall.controller;

import com.fc.mall.dto.CommonResult;
import com.fc.mall.dto.PmsGroupBuy;
import com.fc.mall.dto.PmsGroupBuyParam;
import com.fc.mall.dto.PmsGroupBuyQueryParam;
import com.fc.mall.dto.PmsGroupBuyReq;
import com.fc.mall.exception.ServiceException;
import com.fc.mall.model.PmsProductGroupBuy;
import com.fc.mall.service.PmsGroupBuyService;
import com.fc.mall.util.DateTimeHelper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.ParseException;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 拼团管理Controller
 * Created by dobuy on 2019/8/19.
 */
@Controller
@Api(tags = "PmsGroupBuyController", description = "拼团管理")
@RequestMapping("/groupbuy")
public class PmsGroupBuyController {
    @Autowired
    private PmsGroupBuyService groupBuyService;

    @ApiOperation("创建拼团")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    @ResponseBody
    public Object create(@RequestBody PmsGroupBuyReq req, BindingResult bindingResult) {
        int count = groupBuyService.create(req);
        if (count > 0) {
            return new CommonResult().success(count);
        } else {
            return new CommonResult().failed();
        }
    }

    @ApiOperation("根据拼团id获取拼团编辑信息")
    @RequestMapping(value = "/updateInfo/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object getUpdateInfo(@PathVariable Long id) {
        PmsGroupBuy productResult = groupBuyService.getUpdateInfo(id);
        productResult.setEffectTime(productResult.getEffectTime());
        productResult.setExpiredTime(productResult.getExpiredTime());
        return new CommonResult().success(productResult);
    }

    @ApiOperation("更新商品")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.POST)
    @ResponseBody
    public Object update(@PathVariable Long id, @RequestBody PmsGroupBuyReq req, BindingResult bindingResult) {
        try{
            int count = groupBuyService.update(id, req);
            if (count > 0) {
                return new CommonResult().success(count);
            } else {
                return new CommonResult().failed();
            }
        }catch (ServiceException e){
            return new CommonResult().validateFailed(e.getMessage());
        }
    }

    @ApiOperation("查询商品")
    @RequestMapping(value = "/list", method = RequestMethod.GET)
    @ResponseBody
    public Object getList(PmsGroupBuyQueryParam pmsGroupBuyParam,
                          @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                          @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum) {
        PmsGroupBuyParam param = new PmsGroupBuyParam();
        param.setProductName(pmsGroupBuyParam.getProductName());
        try{
            if(pmsGroupBuyParam.getEffectTimeStart() != null){
                param.setEffectTimeStart(DateTimeHelper.getEpochTimeFromStringFormat(pmsGroupBuyParam.getEffectTimeStart(),DateTimeHelper.SQL_DATETIME));
            }
        } catch (ParseException pe){
            return new CommonResult().validateFailed("生效日期开始格式错误");
        }
        try{
            if(pmsGroupBuyParam.getEffectTimeEnd() != null){
                param.setEffectTimeEnd(DateTimeHelper.getEpochTimeFromStringFormat(pmsGroupBuyParam.getEffectTimeEnd(),DateTimeHelper.SQL_DATETIME));
            }
        } catch (ParseException pe){
            return new CommonResult().validateFailed("生效日期结束格式错误");
        }
        try{
            if(pmsGroupBuyParam.getExpiredTimeStart() != null){
                param.setExpiredTimeStart(DateTimeHelper.getEpochTimeFromStringFormat(pmsGroupBuyParam.getExpiredTimeStart(),DateTimeHelper.SQL_DATETIME));
            }
        } catch (ParseException pe){
            return new CommonResult().validateFailed("过期日期开始格式错误");
        }
        try{
            if(pmsGroupBuyParam.getExpiredTimeEnd() != null){
                param.setExpiredTimeEnd(DateTimeHelper.getEpochTimeFromStringFormat(pmsGroupBuyParam.getExpiredTimeEnd(),DateTimeHelper.SQL_DATETIME));
            }
        } catch (ParseException pe){
            return new CommonResult().validateFailed("过期日期结束格式错误");
        }

        List<PmsGroupBuy> groupBuyList = groupBuyService.list(param, pageSize, pageNum);
        return new CommonResult().pageSuccess(groupBuyList);
    }

    @ApiOperation(value = "删除拼团")
    @RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
    @ResponseBody
    public Object delete(@PathVariable("id") Long id) {
        int count = groupBuyService.delete(id);
        if (count == 1) {
            return new CommonResult().success(null);
        } else {
            return new CommonResult().failed();
        }
    }

    @ApiOperation("创建拼团")
    @RequestMapping(value = "/product/check", method = RequestMethod.GET)
    @ResponseBody
    public Object checkGroupBuyProduct(Long groupBuyId, Long productId) {
        List<PmsProductGroupBuy> actives = groupBuyService.queryAllActiveGroupBuysByProductId(productId);
        boolean onGroupBuy;
        if (groupBuyId == null) {
            onGroupBuy = actives.size() > 0;
        } else {
            onGroupBuy = actives.stream()
                    .filter(groupBuy -> !groupBuy.getId().equals(groupBuyId))
                    .collect(Collectors.toList())
                    .size() > 0;
        }
        return new CommonResult().success(onGroupBuy);
    }
}
